<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\admin\model\Catalog;
use app\admin\model\Banner as BannerModel;
use app\admin\validate\Banner as BannerValidate;
/**
 * Banner管理
 */
class Banner extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input();
            $count = BannerModel::withSearch(['language','keyword'], $input)->count();
            $data  = BannerModel::withSearch(['language','keyword'], $input)
            ->order('sort', 'desc')
            ->page($input['page'], $input['pageSize'])
            ->select();
            return json(['status' => 'success', 'message' => '请求成功', 'data' => $data, 'count' => $count]);
        } else {
            // 分类
            $catalog = Catalog::where('language', $this->request->lang)
            ->where('status', 1)
            ->order('sort', 'desc')
            ->select();
            View::assign('catalog', $catalog);
            return View::fetch();
        }
    }

    /**
     * 保存新建的资源
     */
    public function save()
    {
        try {
            $input = input();
            validate(BannerValidate::class)->scene('save')->check($input);
            $sort  = BannerModel::order('sort','desc')->value('sort');
            $sort  = $sort ? $sort + 1 : 1;
            BannerModel::create([
                'catalog_id'  => $input['catalog_id'],
                'cover'       => $input['cover'],
                'video'       => $input['video'],
                'title'       => $input['title'],
                'detail'      => $input['detail'],
                'content'     => $input['content'],
                'link'        => $input['link'],
                'sort'        => $sort,
                'status'      => $input['status'],
                'language'    => $this->request->lang,
                'create_time' => date('Y-m-d H:i:s'),
            ]);
            $this->cacheClear();
            return json(['status' => 'success', 'message' => '添加成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            validate(BannerValidate::class)->check($input);
            $save  = BannerModel::find($input['id']);
            $save->update_time = date('Y-m-d H:i:s');
            $save->catalog_id  = $input['catalog_id'];
            $save->cover       = $input['cover'];
            $save->video       = $input['video'];
            $save->title       = $input['title'];
            $save->detail      = $input['detail'];
            $save->content     = $input['content'];
            $save->link        = $input['link'];
            $save->status      = $input['status'];
            $save->save();
            $this->cacheClear();
            return json(['status' => 'success', 'message' => '修改成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        try {
            $input = input();
            validate(BannerValidate::class)->scene('delete')->check($input);
            BannerModel::destroy($input['ids']);
            $this->cacheClear();
            return json(['status' => 'success', 'message' => '删除成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 同步主语言数据
     */
    public function synchro()
    {
        $where[] = ['language','=' ,$this->request->langDefault];
        $model = new BannerModel;
        $data = $model::withoutField('id')->where($where)->select();
        if ($data) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key]['language'] = $this->request->lang;
                $data[$key]['catalog_id'] = [];
            }
            Db::startTrans();
            try {
                $model::where('language', $this->request->lang)->delete();
                $model->saveAll($data);
                $this->cacheClear();
                Db::commit();
                return json(['status' => 'success', 'message' => '同步成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 'error', 'message' => '同步失败']);
            }
        } else {
            return json(['status' => 'error', 'message' => '主语言暂无数据']);
        }
    }

    /**
     * 排序
     */
    public function sort()
    {
        try {
            $input = input();
            $sort  = $input['sort'];
            $field = 'id,sort';
            $order = ['sort' => 'desc'];
            $where [] = ['id', '<>', $input['row']['id']]; 
            $where [] = ['language', '=', $this->request->lang]; 
            $newArr[] = ['id' => $input['row']['id'], 'sort' => $sort];
            $largeOp = $sort > $input['row']['sort'] ? '>' : '>=';
            $smallOp = $sort > $input['row']['sort'] ? '<=' : '<';
            $count = BannerModel::where($where)->count() + 1;
            $large = BannerModel::where($where)->where('sort',$largeOp,$sort)->field($field)->order($order)->select()->toArray();
            $small = BannerModel::where($where)->where('sort',$smallOp,$sort)->field($field)->order($order)->select()->toArray();
            $array = array_merge($large,$newArr,$small);
            foreach ($array as $key => $val) {
                if ($key !== 0) $count --;
                BannerModel::where('id', $val['id'])->update(['sort' => $count]);
            }
            $this->cacheClear();
            return json(['status' => 'success', 'message' => '排序成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 复制到其它语言
     */
    public function copyList() {
        if ($this->request->isPost()) {
            $input = input();
            $model = new BannerModel;
            $data  = $input['rows'];
            foreach ($data as $key => $val) {
                $data[$key]['language'] = $input['language'];
                $data[$key]['catalog_id'] = $input['catalog_id'];
                unset($data[$key]['id'], $data[$key]['children']);
            }
            $model->saveAll($data);
            $this->cacheClear();
            return json(['status' => 'success', 'message' => '复制成功']);
        }
    }

    /**
     * 清除缓存
     */
    public function cacheClear() 
    {
        $catalog = Catalog::column('id');
        foreach ($catalog as $key => $id) {
            cache('banner_'.$id, NULL);
        }
    }
}
